package com.example.distschedule.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.distschedule.ResourceTable;
import com.example.distschedule.ScheduleManageAbility;
import com.example.distschedule.bean.Command;
import com.example.distschedule.bean.DeviceResult;
import com.example.distschedule.bean.RespondBase;
import com.example.distschedule.event.MessageEvent;
import com.example.distschedule.rx2.OKHttpUtilsRx2;
import com.example.distschedule.toast.XToastUtils;
import com.example.distschedule.utils.CommandUtil;
import com.example.distschedule.utils.DeviceStateUtil;
import com.example.distschedule.utils.PreferencesUtil;
import com.socks.library.KLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.miscservices.timeutility.Time;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.greenrobot.eventbus.EventBus;
import java.util.Locale;

import static com.example.distschedule.slice.SelectDeviceAbilitySlice.KEY_IS_SET_COMMAND;

/**
 * 智能电饭煲控制页面
 *
 * @since 2022-
 */
public class CookerAbilitySlice extends AbilitySlice {

    private boolean isON = false;
    private Text waterVolume;
    private Text riceVolume;
    private Image switchImg;
    private Slider slider;
    private Slider rslider;
    private String deviceId;
    private boolean isSetCommand = false;
    private  Component appointment;



    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_smartcooker);
        deviceId = intent.getStringParam("deviceId");
        //deviceId="621068a3de9933029be8e65b_RiceCooker";指定设备ID调试
        isSetCommand = intent.getBooleanParam(KEY_IS_SET_COMMAND, false);
        initComponents();
        initDeviceState();
    }

    private void initCookerState() {
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(() -> {
            KLog.i("async task initCookerState run");
            getDeviceInfo();

        });
    }

    private void initDeviceState() {
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        KLog.i(deviceInfo);
                        if (deviceInfo.isSuccess() && deviceInfo.getResult().isOnline()) {
                            // 更新状态
                            String property = deviceInfo.getResult().getProperty();
                            isON = DeviceStateUtil.getRiceMotorStatus(property);

                            String wv=DeviceStateUtil.getwaterVolume(property);
                            String rv=DeviceStateUtil.getriceVolume(property);
                            if (isON) {
                                switchImg.setPixelMap(ResourceTable.Media_icon_switch_on);
                                /*waterVolume.setText(String.format(Locale.CHINA,"%s",wv+"ml"));
                               slider.setProgressValue(Integer.parseInt(wv));
                               riceVolume.setText(String.format(Locale.CHINA,"%s",rv+"克"));
                               rslider.setProgressValue(Integer.parseInt(wv));*/
                            } else {
                                switchImg.setPixelMap(ResourceTable.Media_icon_switch_off);
                              /*  waterVolume.setText(String.format(Locale.CHINA,"%s",0+"ml"));
                                slider.setProgressValue(0);
                                riceVolume.setText(String.format(Locale.CHINA,"%s",0+"克"));
                                rslider.setProgressValue(0);*/

                            }

                        } else {
                            initCookerState();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        // 失败是因为首次配网状态未更新
                        initCookerState();
                    }
                });
    }

    private void getDeviceInfo() {
        Time.sleep(10 * 1000);
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        super.onNext(deviceInfo);
                        KLog.i(deviceInfo);
                        if (deviceInfo.getResult() == null || !deviceInfo.getResult().isOnline()) {
                            XToastUtils.toast("未配网成功，请再次碰一碰重试");
                        }
                    }
                });
    }



    private void initComponents() {
        switchImg = (Image) findComponentById(ResourceTable.Id_smartcooker_image_switch);
        switchImg.setClickedListener(component -> switchListener());
        findComponentById(ResourceTable.Id_smartcooker_img_left).setClickedListener(this::goBack);
        waterVolume = (Text) findComponentById(ResourceTable.Id_smartcooker_text_waterVolume);
        slider = (Slider) findComponentById(ResourceTable.Id_smartcooker_slider_water);
        slider.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {

            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {
                waterVolume.setText(String.format(Locale.CHINA, "%s", slider.getProgress()));
                if (!isSetCommand) {
                    sendCommand(CommandUtil.getCookerStatusCommand(isON,slider.getProgress(),rslider.getProgress()));
                }
            }
        });
        riceVolume = (Text) findComponentById(ResourceTable.Id_smartcooker_text_riceVolume);
        rslider = (Slider) findComponentById(ResourceTable.Id_smartcooker_slider_rice);
        rslider.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {

            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {
                riceVolume.setText(String.format(Locale.CHINA, "%s", rslider.getProgress()));
                if (!isSetCommand) {
                    sendCommand(CommandUtil.getCookerStatusCommand(isON,slider.getProgress(),rslider.getProgress()));
                }
            }
        });
        appointment = findComponentById(ResourceTable.Id_smartcooker_text_appoint);
        appointment.setClickedListener(this::ScheduleManage);


            Image rightIcon = (Image) findComponentById(ResourceTable.Id_smartcooker_img_right);
        // 顶部右侧图标
        if (isSetCommand) {
            rightIcon.setPixelMap(ResourceTable.Media_icon_ok);
            rightIcon.setClickedListener(this::saveCommand);
        }else{
            rightIcon.setClickedListener(this::goInfo);
        }
    }


    private void ScheduleManage(Component component){
        Intent intent=new Intent();
        present(new AddScheduleAbilitySlice(),intent);
    }

    private void saveCommand(Component component) {
        EventBus.getDefault().post(new MessageEvent(MessageEvent.EVENT_GET_COMMAND, deviceId, CommandUtil.getCookerStatusCommand(isON, slider.getProgress(),rslider.getProgress())));
        onBackPressed();
    }

    private void goInfo(Component component) {

        XToastUtils.info("控制智能电饭煲开关");
    }


    private void goBack(Component component) {
        onBackPressed();
    }

    private void switchListener() {
        isON = !isON;
        if (isON) {
            switchImg.setPixelMap(ResourceTable.Media_icon_switch_on);

        } else {
            switchImg.setPixelMap(ResourceTable.Media_icon_switch_off);
        }
        // 是设置日程命令还是发送命令
        if (!isSetCommand) {
            sendCommand(CommandUtil.getCookerStatusCommand(isON, slider.getProgress(),rslider.getProgress()));
        }
    }

    private void sendCommand(Command command) {
        JSONObject body = new JSONObject();
        body.put("commandName", command.getCommandName());
        body.put("serviceId", command.getServiceId());
        body.put("value", command.getValue());
        OKHttpUtilsRx2.INSTANCE.getApi().sendCommand(deviceId, RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JSON.toJSONString(body)))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase>() {
                    @Override
                    public void onNext(RespondBase respond) {
                        super.onNext(respond);
                        if (respond.isSuccess()) {
                            XToastUtils.toast("发送控制命令成功");
                        }
                    }
                });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}